package es.upv.epsa.mobweb.moneyback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;

import es.upv.epsa.mobweb.moneyback.adapters.AccountsListItemAdapter;
import es.upv.epsa.mobweb.moneyback.database.Account;
import es.upv.epsa.mobweb.moneyback.json.JSONParser;

public class AccountsListActivity extends Activity {

	private ListView 			list;
	private TextView 			txtVacia;

	private String				server_url;
	private JSONParser 			jsonParser;
	private ObjectMapper  		mapper 		= new ObjectMapper();

	private MainApplication		app;
	private ArrayList<Account> 	accounts 	= new ArrayList<Account>();
	private ArrayList<String[]> list_data	= new ArrayList<String[]>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accounts_list);

		jsonParser = new JSONParser();
		setWidgets();
		getData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.accounts_list, menu);
		return true;
	}

	private void setWidgets(){
		server_url	= getResources().getString(R.string.server_url) +
		  		  	  getResources().getString(R.string.accounts_url);
		
		app 		= (MainApplication) getApplication();
		list 		= (ListView) 		findViewById(R.id.list);
		txtVacia 	= (TextView) 		findViewById(R.id.txtVacia);

		list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String[] value = (String []) list.getItemAtPosition(position);
				
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), AccountActivity.class);
				intent.putExtra("account_name", value[0]);
				intent.putExtra("friend_id", value[2]);
				intent.putExtra("accountid", value[3]);
				
				startActivity(intent);
			}

		});
	}

	private void getData(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 4);
			jGenerator.writeNumberField("userid", app.getUser().getId());

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(bout.toString(), true).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void parseJSON(String json){
		try {
			JsonFactory jfactory = new JsonFactory();
			JsonParser jparser = jfactory.createJsonParser(json);

			jparser.nextToken();
			while(jparser.nextToken() == JsonToken.START_OBJECT){
				Account a = new Account();
				a = mapper.readValue(jparser, Account.class);
				accounts.add(a);
				
				list_data.add(new String[]{
											a.getName(), 
											"", 
											String.valueOf(a.getFriend()),
											String.valueOf(a.getId())
											}
				);
			}

			jparser.close();
			
			if(accounts.size() == 0){
				list.setVisibility(View.GONE);
				txtVacia.setVisibility(View.VISIBLE);
			}
			
			AccountsListItemAdapter adapter = new AccountsListItemAdapter(this, list_data);
			list.setAdapter(adapter);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class SendJSON extends AsyncTask<Void, Void, Void>{
		String 			json = "";
		boolean 		parse = false;
		String 			data = "";
		ProgressDialog 	dialog;

		public SendJSON(String json, boolean parse){
			this.json = json;
			this.parse = parse;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			data = jsonParser.sendJSON(server_url, json);

			return null;
		}

		@Override
		protected void onPreExecute(){
			dialog = ProgressDialog.show(AccountsListActivity.this, "", "Loading user accounts...", true);
			dialog.setCancelable(false);
			dialog.setOnCancelListener(new OnCancelListener(){

				@Override
				public void onCancel(DialogInterface dialog) {

				}
				
			});
		}

		@Override
		protected void onPostExecute(Void result){
			if(parse)
				parseJSON(data);
			
			dialog.dismiss();
		}
	}

}
